import { Injectable } from '@angular/core';
import { BasicService } from './basic.service';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { SongUrl, Song, Lyric } from 'src/app/routes/entity';
import { map } from 'rxjs/operators';

@Injectable()
export class SongService extends BasicService {

  constructor(private http: HttpClient) {
    super();
  }

  /**
   * 获取音乐播放地址
   *
   * @param ids 歌单 id 集合字符串，例如：'id1,id2,id3,...'
   */
  getSongUrls(ids: string): Observable<SongUrl[]> {
    const url = this.api(`song/url?id=${ids}`);
    return this.http.get(url)
      .pipe(map((res: { data: SongUrl[] }) => res.data));
  }

  /**
   * 获取歌单集合
   *
   * @param songs 歌单信息
   */
  getSongList(songs: Song | Song[]): Observable<Song[]> {
    const songArray = Array.isArray(songs) ? songs.slice() : [songs];
    const ids = songArray.map(song => song.id).join(',');
    return this.getSongUrls(ids)
      .pipe(map(urls => this.generateSongList(songArray, urls)));
  }

  getSongDetail(ids: string): Observable<Song> {
    const url = this.api(`song/detail?ids=${ids}`);
    return this.http.get(url)
      .pipe(map((res: { songs: Song }) => res.songs[0]));
  }

  /**
   * 获取每首歌曲的歌词
   *
   * @param songId 歌曲 ID
   */
  getLyric(songId: number): Observable<Lyric> {
    const url = this.api(`lyric?id=${songId}`);
    return this.http.get(url).pipe(map(
      (res: { [key: string]: { lyric: string } }) => {
        return {
          lyric: res.lrc?.lyric,
          tlyric: res.tlyric?.lyric
        };
      }));
  }

  /**
   * 生成歌单集合
   *
   * @param songs 歌单集合
   * @param urls 歌单播放地址
   */
  private generateSongList(songs: Song[], urls: SongUrl[]): Song[] {
    const result = [];
    songs.forEach(song => {
      const url = urls.find(e => e.id === song.id).url;
      if (url) {
        result.push({ ...song, url });
      }
    });
    return result;
  }
}
